<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\ScoreRuleController;
use App\Models\OnlineRegistration;
use App\Models\OnlineRegistrationOrder;
use App\Models\RegisterVerify;
use App\Validate\OnlineRegistrationValidate;
use Illuminate\Support\Facades\DB;
use SendTemplateSMS;

/**
 * 在线办证控制器
 * Class OnlineRegistration
 * @package app\api\controller
 */
class OnlineRegistrationController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();
        $this->validate = new OnlineRegistrationValidate();
        $this->model = new OnlineRegistration();
    }


    /**
     * 发送验证码
     * @param tel     电话号码
     * @param key     电话号码+tel_key    后的MD5值     md5(13030303030.tel_key)
     * @param state   类型  在线办证 1
     */
    public function sendVerify()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('send')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $number = get_rnd_number(6); //获取验证码
        $obj = new SendTemplateSMS();
        //选择模板编号
        $tel = $this->request->tel;
        $state = $this->request->state;
        $registerVerifyObj = new RegisterVerify();
        //   $template = $registerVerifyObj->getTemplate($state);
        //   $result = $obj->sendTemplateSMS($tel, [$number, '5分钟'], $template); //手机号码，替换内容数组，模板ID

        //测试环境下，验证码全是6个0
        $result['code'] = '200';
        $number = '000000';

        $expir = strtotime("+5 minutes");
        $expir_time = date('Y-m-d H:i:s', $expir);
        if ($result['code'] == '200') {
            //发送成功之后，先删除之前此电话号码的验证码 + 储蓄验证码
            $registerVerifyObj->addVerify($tel, $number, $expir_time);

            return $this->returnApi(200, '发送成功', true);
        } else {
            return $this->returnApi(202, '验证码发送失败');
        }
    }

    /**
     * 获取证件类型
     */
    public function getCertificateType()
    {
        $res = $this->model->getCertificateType();

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(12);

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取在线办证类型
     * @param certificate_type  证件类型  1 为身份证  2 为其他证
     */
    public function getCardType()
    {
        $certificate_type = request()->input('certificate_type', 1);

        if ($certificate_type == 1) {
            $res = $this->model->getCardByFront();
        } else {
            $res = $this->model->getCardByFrontOther();
        }

        if ($res) {
            // sort($res);
            $res = array_values($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取下拉选项参数
     */
    public function getOnlineParam()
    {
        $data['culture'] = $this->model->getCulture();
        $data['position'] = $this->model->getPosition();

        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 获取动态参数
     *
     * 配置界面选项，多个用“|”链接     1.头像(弃用) 2.居住地 3.身份证正反面 4.电子邮箱 5.邮政编码 6.座机号码 7.读者职业 8.文化程度 9.工作单位 10.备注
     */
    public function getDynamicParam()
    {
        $data = $this->model->dynamicParam();
        $data = $data ? explode('|', $data) : [];
        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 读者证-办证接口
     * @param $certificate_type   证件类型  1 为身份证  2 为其他证
     * @param $id_card   身份证        必传
     * @param $username  读者姓名      必传
     * @param $card_type 读者证类型     必传
     * @param $workunit  工作单位
     * @param $province  省
     * @param $city      市
     * @param $district  区
     * @param $street    街道(弃用)
     * @param $address   详细地址
     * @param $zip       邮编
     * @param $phone     电话号码
     * @param $tel       手机号码       必传
     * @param $culture_id   文化程度id       必传
     * @param $culture   文化程度       必传
     * @param $position_id  职业id           必传
     * @param $position  职业           必传
     * @param $email     电子邮箱
     * @param $remark    备注
     * @param $verify  验证码
     * @param $card_front  身份证正面
     * @param $card_reverse  身份证反面
     */
    public function registration()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('online_register')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];

        if ($this->request->certificate_type == 2 && $this->request->card_type != 28) {
            return $this->returnApi(201, '读者证号类型错误');
        }
        if ($this->request->email && !is_email($this->request->email)) {
            return $this->returnApi(202, '邮箱格式不正确');
        }

        //单独验证身份证正反面是否必传
        $card_front = $this->request->card_front;
        $card_reverse = $this->request->card_reverse;
        $dynamic_param = $this->model->dynamicParam();
        $dynamic_param = $dynamic_param ? explode('|', $dynamic_param) : [];
        if (in_array(3, $dynamic_param) && (empty($card_front) || empty($card_reverse))) {
            return $this->returnApi(201, '请上传身份证正反面');
        }

        $province = $this->request->input('province', '');
        $city = $this->request->input('city', '');
        $district = $this->request->input('district', '');
        $street = $this->request->input('street', '');
        $address = $this->request->input('address', '');
        //单独验证地址是否必传
        if (in_array(2, $dynamic_param)) {
            if ((empty($province) || empty($city) || empty($district) || empty($address)) && !(empty($province) && empty($city) && empty($district) && empty($address))) {
                return $this->returnData(201, '地址信息填写错误');
            }
        }

        //判断是否验证图书馆接口
        //   if (config('other.is_validate_lib_api')) {
        //判断此身份证是否办过卡
        $libApi = $this->getLibApiObj();

        if ($this->request->id_card != '510106199007283002') {
            //判断 身份证 是否在所有一卡通办过证，因为在所有一卡通办过证的，在本馆没办过证的身份证，也办不起，只能办理 “其他” 证
            $id_card_cloud_exist = $libApi->validateIdnoIsExist($this->request->id_card);
            if ($id_card_cloud_exist['code'] == 203) {
                return $this->returnApi(202, $id_card_cloud_exist['msg']);
            }

            $id_card_exist = $libApi->getReaderPageInfoByIdno($this->request->id_card);
            if ($id_card_exist['code'] == 200) {
                return $this->returnApi(202, '此身份证号码已办理过读者证，请勿重复办理');
            }
            if ($id_card_exist['code'] == 203) {
                return $this->returnApi(202, $id_card_exist['msg']);
            }

            //在一卡通办过证，在本馆未办过证，说明只在其他馆办过，在本馆就只能办理“其他” 证
            if ($id_card_cloud_exist['code'] == 200 && $id_card_exist['code'] == 202 && $this->request->certificate_type == 1) {
                $card_status['msg'] = $this->model->repetitionCertificateMsg;
                return $this->returnApi(202, $card_status['msg']);
            }
            //  }

            $is_exists = OnlineRegistration::where('id_card', $this->request->id_card)->where('is_pay', 1)->first();
            if ($is_exists) {
                return $this->returnApi(202, '此身份证号码已在线申请过读者证，请到个人中心进行支付！');
            }
        }

        $remark = $this->request->input('remark', '');
        if (mb_strlen($remark) > 300) {
            return $this->returnApi(202, '备注字数不能超过300字');
        }

        DB::beginTransaction();
        try {
            RegisterVerify::where('phone', $this->request->tel)->delete(); //验证成功，删除验证码

            $cash = $this->model->getCardByFrontList($this->request->card_type)['cash'];

            //添加在线办证订单表
            $order_id = null;
            $reader_id = null; //读者证号
            if (!empty($cash) && $cash != '0.00') {
                $onlineRegistrationOrderModelObj = new OnlineRegistrationOrder();
                $order_number = get_order_id();; //获取订单号

                $onlineRegistrationOrderModelObj->add([
                    'order_number' => $order_number,
                    'user_id' =>  request()->input('user_id', ''),
                    'account_id' => request()->input('account_id', ''),
                    'price' => $cash,
                    'dis_price' => $cash,
                    //'discount' => $discount,
                    'is_pay' => 1,
                    'payment' => 1
                ]);
                $order_id = $onlineRegistrationOrderModelObj->id; //获取订单id
                $msg = '提交成功';
            } else {
                //获取读者证号
                $reader_id = $this->model->getReaderId($this->request->card_type);
                if (empty($reader_id)) {
                    throw  new \Exception('获取读者证号失败');
                }
                $msg = '读者证办理成功！读者证号为【' . $reader_id . '】，初始密码为身份证号码中间8位生日，是否立即绑定？';
            }

            $data['source'] = 1;
            $data['reader_id'] = $reader_id;
            $data['order_id'] = $order_id;
            $data['certificate_type'] = $this->request->certificate_type;
            $data['certificate_num'] = $this->request->certificate_type == 1 ? $this->request->id_card : $this->request->id_card . 'Z';
            $data['id_card']  = $this->request->id_card;
            $data['username'] = $this->request->username;
            $data['card_type'] = $this->request->card_type;
            $data['cash'] = $cash;
            $data['tel'] = $this->request->tel;
            $data['birthday'] = get_user_birthday_by_id_card($this->request->id_card);
            $data['sex'] = get_user_sex_by_id_card($this->request->id_card);
            $data['workunit'] = request()->input('workunit', '');
            $data['province'] = $province ? $province : null;
            $data['city'] = $city ? $city : null;
            $data['district'] = $district ? $district : null;
            $data['street'] = $street ? $street : null;
            $data['address'] = $address ? $address : null;
            $data['zip'] = request()->input('zip', '');
            $data['phone'] = request()->input('phone', '');
            $data['email'] = request()->input('email', '');
            $data['culture_id'] = request()->input('culture_id', '');
            $data['culture'] = request()->input('culture', '');
            $data['position_id'] = request()->input('position_id', '');
            $data['position'] = request()->input('position', '');
            $data['is_pay'] = empty($order_id) ? 2 : 1; //无订单就是已支付
            $data['status'] = empty($order_id) ? 3 : 2; //无订单就是无需领取
            $data['pay_way'] = 2;
            $data['node'] = empty($order_id) ? 1 : 2; //无订单就是写入成功
            $data['remark'] = addslashes($remark);
            $data['user_id'] = $user_id;
            // $data['certificate_manage_id'] = $this->request->manage_id'];//办证管理员id


            //如果是临时图片，移动到指定位置
            $host_addr = public_path('uploads');
            if ($card_front  && strpos($card_front, 'temp_img') !== false) {
                $card_front_pathinfo = pathinfo($card_front);
                $move_file = 'card_img/' . date('Y-m-d') . '/' . uniqid() . '.' . $card_front_pathinfo['extension'];
                $card_front_res = move_uploaded_files($host_addr . '/' . $card_front, $host_addr . '/' . $move_file);
                if (!$card_front_res) {
                    throw new \Exception('身份证图片保存失败');
                }
                $card_front = $move_file;
            }
            //如果是临时图片，移动到指定位置
            if ($card_reverse  && strpos($card_reverse, 'temp_img') !== false) {
                $card_reverse_pathinfo = pathinfo($card_reverse);
                $move_file = 'card_img/' . date('Y-m-d') . '/' . uniqid() . '.' . $card_reverse_pathinfo['extension'];
                $card_reverse_res = move_uploaded_files($host_addr . '/' . $card_reverse, $host_addr . '/' . $move_file);
                if (!$card_reverse_res) {
                    throw new \Exception('身份证图片保存失败');
                }
                $card_reverse = $move_file;
            }

            $data['card_front'] = $card_front; //身份证正面
            $data['card_reverse'] = $card_reverse; //身份证反面

            $this->model->add($data);


            //判断是否验证图书馆接口
            if (config('other.is_validate_lib_api')) {
                if (!empty($reader_id)) {
                    $card_status = $libApi->readerIdAdd($data);
                    if ($card_status['code'] !== 200) {
                        $msg = mb_substr($card_status['msg'], 0, 36);
                        if ($msg == $this->model->contrastMsg) {
                            $card_status['msg'] = $this->model->repetitionCertificateMsg;
                        }
                        throw  new \Exception($card_status['msg']);
                    }
                }
            }
            DB::commit();
            return $this->returnApi(200, $msg, true, [
                'order_id' => $order_id,
                'order_number' => !empty($order_number) ? $order_number : null,
                'create_time' => date('Y-m-d H:i:s'),
                'price' => $cash,
                'reader_id' => empty($order_number) ? $reader_id : null, //下订单的数据不返回
                // 'password' => empty($order_number) ? substr($this->request->id_card, 6, 8) : null, //下订单的数据不返回
                'password' => empty($order_number) ? '123456' : null, //下订单的数据不返回
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }

    /**
     * 用户办证历史
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     * @param token int 用户token
     */
    public function historyList()
    {
        $this->changeOrderStatus(); //处理失效订单

        $user_id = request()->user_info['id'];
        $page = intval(request()->input('page', 1)) ?: 1;
        $limit = intval(request()->input('limit', 10)) ?: 10;

        $res = $this->model
            ->select("id", "reader_id", "username", "card_type", "id_card", "create_time", "status", "is_pay", 'cash', "order_id")
            ->where('user_id', $user_id)
            ->orderByDesc("create_time")
            ->paginate($limit);

        if ($res->isEmpty()) {
            return $this->returnApi(203, '暂无数据');
        }
        $res = $res->toArray();

        foreach ($res['data'] as $key => $val) {
            //判断是否支付
            // $res['data'][$key]['status'] = $this->orderStatus($val['is_pay'], $val['order_id'], $val['status']);
            $res['data'][$key]['card_name'] = $this->model->getCardByFrontList($val['card_type'])['card_name'];
            $res['data'][$key]['expire_time'] = strtotime("+30 min", strtotime($val['create_time'])); //过期时间，默认是创建后30分钟
        }

        return $this->returnApi(200, '获取成功', true, $res);
    }
    /**
     * 获取订单状态
     * status 1 已领取  2 待领取  3 无需领取   4、已注销  5、待支付  6 支付异常  7 订单已失效
     */
    public function changeOrderStatus()
    {
        $onlineRegistrationOrderModelObj = new OnlineRegistrationOrder();
        //判断是否过期
        $order_info = $onlineRegistrationOrderModelObj->select('id')->where('is_pay', 1)->where('create_time', '<', date('Y-m-d H:i:s', strtotime("-30 min")))->get()->toArray();
        foreach ($order_info as $key => $val) {
            $onlineRegistrationOrderModelObj->where('id', $val['id'])->update(['is_pay' => 4, 'change_time' => date('Y-m-d H:i:s')]);
            $this->model->where('order_id', $val['id'])->update(['is_pay' => 4, 'change_time' => date('Y-m-d H:i:s')]);
        }
    }

    /**
     * 办证详情
     * @param id 在线办证id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $this->changeOrderStatus(); //处理失效订单

        $id = request()->input('id');

        if (!$id) {
            return $this->returnApi(201, '参数传递错误');
        }

        $res = $this->model
            ->select("reader_id", "card_type", "province", "city", "district", "street", "address", "username", "culture", "position", "tel", "id_card", "zip", "phone", "email", "create_time", "status", "is_pay", "order_id", "cash", "certificate_type")
            ->find($id);

        if (!$res) {
            return $this->returnApi(203, '暂无数据');
        }
        $res['certificate_name'] = $res['certificate_type'] == 1 ? '身份证' : '其他';
        $res['card_name'] = $this->model->getCardByFrontList($res['card_type'])['card_name'];
        //$res['status'] = $this->orderStatus($res['is_pay'], $res['order_id'], $res['status']);

        $res['expire_time'] = strtotime("+30 min", strtotime($res['create_time'])); //过期时间，默认是创建后30分钟

        return $this->returnApi(200, '获取成功', true, $res);
    }
}
